package com.hiultra.archive.utils.tool;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiultra.archive.domain.vo.ArchiveStocktakingTaskIssuedVo;
import com.hiultra.archive.domain.vo.HouseLocationNoInfoIssuedVo;
import com.hiultra.archive.domain.vo.SendParamVo;
import com.hiultra.archive.utils.sgsm.SM2Util;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class ToolUtils {

    @Autowired
    private RestTemplate restTemplate;

    //发送请求
    public static Map<String, Object> sendHttp(String url, String jsonStr) {
        String result = HttpRequest.post(url).body(jsonStr).timeout(20000).execute().body();

        System.out.println("result" + result);
        JSONObject resultsonRes = JSONObject.parseObject(result.replaceAll("[\\(\\)]", ""));
        return resultsonRes;
    }

    /**
     * 检测IP地址是否能ping通
     *
     * @param ip      IP地址
     * @param timeout 检测超时（毫秒）
     * @return 是否ping通
     */
    public static boolean pingConnect(String ip, int timeout) {
        try {
            return InetAddress.getByName(ip).isReachable(timeout); // 当返回值是true时，说明host是可用的，false则不可。
        } catch (Exception ex) {
            return false;
        }
    }

    public static <S, T> List<T> copyList(List<S> sources, Supplier<T> target) {
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = target.get();
            BeanUtils.copyProperties(source, t);
            list.add(t);
        }
        return list;
    }

    public static <S, T> T convertEntity(S source, Supplier<T> target) {
        T t = target.get();
        BeanUtils.copyProperties(source, t);
        return t;
    }

    /**
     * 两位下级编号
     */
    public static synchronized String get00NextCode(String code) {
        if (code.length() < 2) {
            return "00";
        }
        String temps = code.substring(code.length() - 2, code.length());
        int tempi = Integer.parseInt(temps);
        if (tempi == 99) {
            return "00";
        } else {
            return String.format("%02d", tempi);
        }
    }

    public static HashMap sendPostRequest(String interfaceNo, String urlIp, String url, String mgs, String requestData, String pubKey, String priKey) throws ServiceException {

//        //验证是否通讯
//        if (!pingConnect(urlIp, 1000)) {
//            throw new ServiceException(mgs + "服务器离线，请稍后重试！");
//        }
        try {
            RestTemplate restTemplate = new RestTemplate();
            // 公钥加密
            String encryptedData = new SM2Util().encryptBySM2(requestData, pubKey);
            System.out.println(mgs + "入参公钥加密后:**********" + encryptedData);

            //入参
            SendParamVo sendParamVo = new SendParamVo();
            sendParamVo.setChannelCode("DAS");
            sendParamVo.setInteCode(interfaceNo);
            sendParamVo.setData(encryptedData);

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(sendParamVo);
            System.out.println("完整的字符串：" + jsonString);
            String resultEncryption = restTemplate.postForObject(url, sendParamVo, String.class);
//            // 私钥解密获取结果
//            String decryptedResult = new SM2Util().decryptBySM2(resultEncryption, priKey);
//            System.out.println(mgs + "结果私钥解密后:**************" + decryptedResult);
            HashMap hashMap = JSON.parseObject(resultEncryption, HashMap.class);
            System.out.println(hashMap);
            if (hashMap == null || !hashMap.containsKey("code") || !hashMap.get("code").equals("00000")) {
                System.out.println(mgs + "失败");
                throw new ServiceException(hashMap.get("message").toString());
            }
            return hashMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("HTTP请求异常: " + e.getMessage());
        }
    }

    /**
     * 将List<Bean> 转化成List<Map>
     *
     * @return
     */
    public static List<Map<String, Object>> listBeanToMap(List list) {
        ArrayList<Map<String, Object>> mapList = new ArrayList<>(list.size());
        for (Object obj : list) {
            mapList.add(BeanUtil.beanToMap(obj));
        }
        return mapList;
    }
}
